package me.chnxan.biz;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import me.chnxan.idm.User;
import me.chnxan.idm.UserManager;

@Controller
@RequestMapping("/portal.do")
public class PortalController {
	@Autowired
	private UserManager userManager;
	
	@RequestMapping(params = "m=login")
	public void login(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		response.setCharacterEncoding("UTF-8");
		String uid = request.getParameter("username");
		//权宜之计，暂时以uid 替代username
		String code = request.getParameter("code");
		String rand = (String) request.getSession().getAttribute("rand");
		String result = "false";
		if(code.equals(rand)){
			User user = userManager.get(Long.parseLong(uid));
			if(user != null){
				request.getSession().setAttribute("currentUser", user);
				result = "true";
			}else{
				result = "false,info:\"帐号不存在\"";
			}
		}else{
			result = "false,info:\"验证码错误\"";
		}
		response.getWriter().println("{success:" + result + "}");
	}
	
	@RequestMapping(params = "m=logout")
	public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		response.setCharacterEncoding("UTF-8");
		request.getSession().removeAttribute("currentUser");
		request.getSession().removeAttribute("currentGroup");
		request.getSession().removeAttribute("currentActor");		
		response.sendRedirect("pages/portal/main.jsp");
	}
	
	@RequestMapping(params = "m=getRecord")
	public void getRecord(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		response.setCharacterEncoding("UTF-8");
		String id = request.getParameter("id");
		StringBuffer json = new StringBuffer("");
		if("account".equals(id)){
			List<User> list = userManager.find("from User u where isValid=?", true);;
			if(list != null && list.size() > 0) {
				json.append( "{'totalProperty':'" + list.size() + "','root':[" );
				for (int i = 0; i < list.size(); i++) {
					if(i != 0) json.append(",");
					User user = list.get(i);
					json.append("{");
					json.append("'uid':'");
					json.append(user.getUid());
					json.append("', ");
					json.append("'password':'");
					json.append(user.getPassword());
					json.append("'");
					json.append("}");
				}
				json.append("]}");
			}else json.append("{'totalProperty':'0','root':[]}");
		}else{
			json.append("{'totalProperty':'0','root':[]}");
		}
		response.getWriter().println(json.toString());
	}
}
